﻿using CommunityToolkit.Mvvm.ComponentModel;
using OxyPlot.CatExtension.Skia;
using OxyPlot.Legends;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace OxyPlot.CatExtension.WpfTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    [INotifyPropertyChanged]
    public partial class MainWindow : Window
    {
        const int length = 100_0000;
        private readonly float[] _xArr = Enumerable.Range(0, length).Select(x => (float)x).ToArray();
        private readonly float[] _yArr = Enumerable.Range(0, length).Select(x => (float)x).ToArray();

        private readonly SimdLineSeriesF _series;
        [ObservableProperty]
        public partial string Duration { get; set; } = "";
        [ObservableProperty]
        public partial PlotModel Model { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            Model = new PlotModel();            

            _series = new SimdLineSeriesF() { Title = "Test" };


            Model.Series.Add(_series);
            Model.Legends.Add(new Legend());

            DataContext = this;
            Task.Run(Test);
        }

        public async Task Test()
        {
            const int delay = 50;
            while (true)
            {                
                Random.Shared.Shuffle(_yArr);
                var sw = Stopwatch.StartNew();
                lock (Model.SyncRoot)
                {
                    _series.ClearPoints();
                    _series.AddPoints(_xArr, _yArr);

                    Model.InvalidatePlot(true);
                }
                sw.Stop();
                var ms = sw.Elapsed.TotalMilliseconds;
                Duration = $"{ms:f6}ms";

                ms = delay - ms;
                if(ms > 0)
                {
                    await Task.Delay((int)ms);
                }                
            }
        }
    }
}